package com.springTxStudy.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages = "com.springTxStudy")
@PropertySource("classpath:jdbc.properties")
//@EnableAspectJAutoProxy     // 开启aspectj注解的支持
@EnableTransactionManagement    // 开启事务注解的支持
public class JavaConfig {

    // druid连接池实例化
    @Bean
    public DruidDataSource druidDataSource(@Value("${ioCStudy.url}") String url, @Value("${ioCStudy.driverClassName}") String driverClassName, @Value("${ioCStudy.username}") String username, @Value("${ioCStudy.password}") String password) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }

    // jdbcTemplate实例化
    @Bean
    public JdbcTemplate jdbcTemplate(DruidDataSource druidDataSource) {
        return new JdbcTemplate(druidDataSource);
    }

    // 事务管理器，TransactionManager是所有事物管理器的父接口
    @Bean
    public TransactionManager transactionManager(DruidDataSource druidDataSource) {
        // DataSourceTransactionManager内部要进行的事物的操作，基于druid连接池
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(druidDataSource);
        return dataSourceTransactionManager;
    }

}
